﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StateGrid;
using StateGrid.User;
using StateGrid.ZWQK;
using StateGrid.GlobalVariables;
using iTextSharp.text.pdf;
using StateGrid.OperationLog;

public partial class EditPM : System.Web.UI.Page
{
    /// <summary>
    /// 操作对象
    /// </summary>
    private ZWQK_DAO zwqkDAO = new ZWQK_DAO();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!UserManageDAO.IsLogin((User)Session["login"]))
        {
            GlobalMethod.RedirectLogin(Response);
            return;
        }
        if (!this.IsPostBack)
        {
            //this.TextBox1.Text=Request["currentCatalog"].ToString();
            this.BindData();
        }
    }

    /// <summary>
    /// 绑定数据
    /// </summary>
    private void BindData()
    {
        String currentWJM = (String)Request["wjm"];
        if (null == currentWJM)
        {
            return;
        }
        ZWQK_PM zwqkPM = this.zwqkDAO.getZwqkPMByWjm(currentWJM);

        if (null == zwqkPM)
        {
            return;
        }
        //根据索引编码获取索引目录信息
        ZWQK_SYML zwqkSYML = this.zwqkDAO.getZwqkSYMLBySybm(zwqkPM.sybm);

        //中文名称
        this.zwmcTextBox.Text = zwqkSYML.zwmc;
        //外文名称
        this.wwmcTextBox.Text = zwqkSYML.wwmc;
        //中文篇名
        this.zwpmTextBox.Text = zwqkPM.zwpm;
        //外文篇名
        this.wwpmTextBox.Text = zwqkPM.wwpm;
        //年份
        this.nfTextBox.Text = zwqkPM.nf;
        //期号
        this.qhTextBox.Text = zwqkPM.qh;
        //索引编码
        this.sybmTextBox.Text = zwqkPM.sybm;
        //页数
        this.ysTextBox.Text = zwqkPM.ys.ToString();
        //文件名
        this.wjmHyperLink.Text = zwqkPM.wjm;
        this.wjmHyperLink.NavigateUrl = GlobalResource.VIEW_PAGE + "?fileName="+zwqkPM.wjm;

        //原文件名
        this.ywjmHiddenField.Value = zwqkPM.ywjm;

        //最后一个点的位置
        int dotEndIndex = zwqkPM.wjm.LastIndexOf('.');
        //篇号
        this.phTextBox.Text = zwqkPM.wjm.Substring(dotEndIndex - 3, 3);

        //作者
        this.zzTextBox.Text = zwqkPM.zz;
        //作者单位
        this.zzdwTextBox.Text = zwqkPM.zzdw;
        //中文篇名
        this.zwpmTextBox.Text = zwqkPM.zwpm;
        //外文篇名
        this.wwpmTextBox.Text = zwqkPM.wwpm;
        //中文文摘
        this.zwwzTextBox.Text = zwqkPM.zwwz;
        //中文主题词
        this.zwztcTextBox.Text = zwqkPM.zwztc;
        //外文文摘
        this.wwwzTextBox.Text = zwqkPM.wwwz;
        //外文主题词
        this.wwztcTextBox.Text = zwqkPM.wwztc;

        //国图分类
        this.gtflTextBox.Text = zwqkPM.gtfl;
        //文献标识
        this.wxbsTextBox.Text = zwqkPM.wxbs;
        //登录人
        this.dlrTextBox.Text = zwqkPM.dlr;
        //开本
        this.kbTextBox.Text = zwqkPM.kb;

        this.SetPreAndNextPM();
    }
    
    /// <summary>
    /// 重新绑定数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void resetButton_Click(object sender, EventArgs e)
    {
        this.BindData();
    }

    /// <summary>
    /// 修改提交
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void submitButton_Click(object sender, EventArgs e)
    {
        if (!this.ValidateZWPM())
        {
            return;
        }

        //验证文件
        if (!this.ValidateYWJMFileUpload())
        {
            return;
        }

        //获取中文篇名信息
        ZWQK_PM zwqkPM = this.GetZWQK_PM();
        //判断有无文件，有则更改原文件名
        if (null != this.ywjmFileUpload.FileName && !"".Equals(this.ywjmFileUpload.FileName))
        {
            zwqkPM.ywjm = this.ywjmFileUpload.FileName;
        }
        //更新中文篇名信息
        if (this.zwqkDAO.updateZwqkPMByWJM(zwqkPM,((StateGrid.User.User)Session["login"]).name))
        {

            //Response.Write("<Script>alert('篇名信息更新成功')</Script>");
            NextPM();
        }
        else
        {
            String message = "错误：添加中文期刊篇名信息失败";
            Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
            return;
        }
    }

    /// <summary>
    /// 从页面中读取片名的信息
    /// </summary>
    /// <returns>返回片名对象</returns>
    private ZWQK_PM GetZWQK_PM()
    {
        User user = (User)Session["login"];
        //登陆超时则退到登录页
        if (null == user)
        {
            Response.Write(" <script> top.location = '" + GlobalResource.LOGIN_PAGE + "' </script> ");
            return null;
        }

        ZWQK_PM zwqkPM = new ZWQK_PM();

        //登录人
        zwqkPM.dlr = user.name;
        //索引编码
        zwqkPM.sybm = this.sybmTextBox.Text.Trim();
        //年份
        zwqkPM.nf = this.nfTextBox.Text.Trim();
        //期号
        zwqkPM.qh = this.qhTextBox.Text.Trim();
        //页数
        try
        {
            zwqkPM.ys = Int32.Parse(this.ysTextBox.Text.Trim());
        }
        catch (Exception)
        {
        }

        //文件名
        zwqkPM.wjm = this.wjmHyperLink.Text.Trim();

        //原文件名
        zwqkPM.ywjm = this.ywjmHiddenField.Value.Trim();

        //中文篇名
        zwqkPM.zwpm = this.zwpmTextBox.Text.Trim();
        //外文篇名
        zwqkPM.wwpm = this.wwpmTextBox.Text.Trim();
        //作者
        zwqkPM.zz = this.zzTextBox.Text.Trim();
        //作者单位
        zwqkPM.zzdw = this.zzdwTextBox.Text.Trim();
        //开本
        zwqkPM.kb = this.kbTextBox.Text.Trim();
        //中文文摘
        zwqkPM.zwwz = this.zwwzTextBox.Text.Trim();
        //外文文摘
        zwqkPM.wwwz = this.wwwzTextBox.Text.Trim();
        //中文主题词
        zwqkPM.zwztc = this.zwztcTextBox.Text.Trim();
        //外文主题词
        zwqkPM.wwztc = this.wwztcTextBox.Text.Trim();

        //国图分类
        zwqkPM.gtfl = this.gtflTextBox.Text.Trim();
        //文献标识
        zwqkPM.wxbs = this.wxbsTextBox.Text.Trim();
        //更新日期
        zwqkPM.gxrq = DateTime.Today;

        return zwqkPM;
    }

    /// <summary>
    /// 验证中文篇名文本框
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateZWPM()
    {
        Boolean flag = true;
        this.errorLabel.Text = "";
        if (null == this.zwpmTextBox.Text || "".Equals(this.zwpmTextBox.Text.Trim()))
        {
            this.errorLabel.Text = "错误：中文篇名不能为空";
            flag = false;
        }

        //验证篇名是否已存在
        if (!this.zwqkDAO.ValidateZWQK_PM(this.wjmHyperLink.Text, this.zwpmTextBox.Text.Trim()))
        {
            this.errorLabel.Text = "错误：该中文篇名已存在";
            flag = false;
        }
        return flag;
    }

    protected void zzTextBox_TextChanged(object sender, EventArgs e)
    {
        this.zzTextBox.Text = GlobalMethod.Semicolon(this.zzTextBox.Text.Trim());
    }

    protected void zzdwTextBox_TextChanged(object sender, EventArgs e)
    {
        this.zzdwTextBox.Text = GlobalMethod.Semicolon(this.zzdwTextBox.Text.Trim());
    }

    protected void zwztcTextBox_TextChanged(object sender, EventArgs e)
    {
        this.zwztcTextBox.Text = GlobalMethod.Semicolon(this.zwztcTextBox.Text.Trim());
    }
    protected void wwztcTextBox_TextChanged(object sender, EventArgs e)
    {
        this.wwztcTextBox.Text = GlobalMethod.Semicolon(this.wwztcTextBox.Text.Trim());
    }

    /// <summary>
    /// 验证并上传文件
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateYWJMFileUpload()
    {
        int pageCount = 0;
        this.errorLabel.Text = "";
        Boolean flag = true;
        if (null == this.ywjmFileUpload || !this.ywjmFileUpload.HasFile)
        {
            //this.errorLabel.Text = "错误：请选择上传的文件";
            return true;
        }
        else
        {
            if (!this.ywjmFileUpload.FileName.EndsWith(".PDF", true, null))
            {
                this.errorLabel.Text = "错误：请选择PDF类型文件";
                flag = false;
            }
            else
            {
                PdfReader pdf = new PdfReader(this.ywjmFileUpload.FileBytes);
                if (null != pdf)
                {
                    //文件大小不能超过10M
                    if (pdf.FileLength >= 10 * 1024 * 1024)
                    {
                        this.errorLabel.Text = "错误：选择的文件大小超过了10M";
                        pdf.Close();
                        return false;
                    }

                    pageCount = pdf.NumberOfPages;
                }
                
                pdf.Close();
            }
        }
        if (flag)
        {
            if (!OperationFile.Upload(this.ywjmFileUpload, this.wjmHyperLink.Text))
            {
                this.errorLabel.Text = "错误：上传文件失败";
                flag = false;
            }
            else
            {
                this.ysTextBox.Text = pageCount.ToString();
                this.ywjmHiddenField.Value = this.ywjmFileUpload.FileName;
            }
        }
        return flag;
    }


    /// <summary>
    /// 设置前一篇和后一篇的链接
    /// </summary>
    private void SetPreAndNextPM()
    {
        //上一篇
        String pre = this.GetDirectionPM(-1);
        if (null != pre)
        {
            this.preHyperLink.NavigateUrl = GlobalZWQK.EDITPM_PAGE + "?wjm=" + pre;
        }

        //下一篇
        String next = this.GetDirectionPM(1);
        if (null != next)
        {
            this.nextHyperLink.NavigateUrl = GlobalZWQK.EDITPM_PAGE + "?wjm=" + next;
        }

        //返回链接
         String currentWJM = (String)Request["wjm"];
         String sybm = (currentWJM.Split('-'))[0];
         this.backHyperLink.NavigateUrl = GlobalZWQK.LISTPM_PAGE + "?sybm=" + sybm;
    }
    /// <summary>
    /// 修改下一篇
    /// </summary>
    private void NextPM()
    {
        String wjm = this.GetDirectionPM(1);
        if (null == wjm)
        {
            return;
        }
        else
        {
            Response.Redirect(GlobalZWQK.EDITPM_PAGE + "?wjm=" + wjm);
        }
    }

    /// <summary>
    /// 获取上一篇下一篇的文件名
    /// </summary>
    /// <param name="direction">上一篇：1;下一篇:-1</param>
    /// <returns></returns>
    private String GetDirectionPM(int direction)
    {
        String wjm = this.wjmHyperLink.Text.Trim();
        int position = wjm.LastIndexOf("-");

        //获取文件名的前半部分
        String s1 = wjm.Substring(0, position + 1);
        //流水号
        String s2 = wjm.Substring(position + 1, 3);
        s2 = FormatPH(s2, direction);

        wjm = s1 + s2 + ".PDF";
        //如果是最后一篇则不跳转
        ZWQK_PM zwqkPM = zwqkDAO.getZwqkPMByWjm(wjm);
        if (null == zwqkPM)
        {
            return null;
        }
        //Response.Redirect(GlobalZWQK.EDITPM_PAGE + "?wjm=" + wjm);
        return wjm;
    }
    /// <summary>
    /// 查找下一篇的流水号
    /// </summary>
    /// <param name="s"></param>
    /// <param name="direction">方向</param>
    /// <returns></returns>
    private String FormatPH(String s,int direction)
    {
        int ph = 0;

        try
        {
            ph = Int32.Parse(s);
        }
        catch (Exception)
        {
            return null;
        }
        //当前篇号+1
        ph += direction;

        s = ph.ToString();
        //长度为1
        if (s.Length == 1)
        {
            s = "00" + s;
        }
        else if (s.Length == 2)
        {
            s = "0" + s;
        }

        return s;
    }
}